<?
    class Error {
        protected $_type = 'error';
        protected $_title = '';
        protected $_message = '';
        
        function __construct($title,$message,$type = 'error') {
            $this->_type = $type;
            $this->_title = $title;
            $this->_message = $message;
        }
        
        function Show() {
            switch ($this->_type) {
                case 'success': SuccessMessage::Show($this->_title,$this->_message); break;
                case 'warning': WarningMessage::Show($this->_title,$this->_message); break;
                case 'info': InfoMessage::Show($this->_title,$this->_message); break;
                case 'error': ErrorMessage::Show($this->_title,$this->_message); break;
            }
        }
    }
    class AuthManager {
        const NO_ERROR = 0;
        const ACCOUNT_EXPIRED = 1;
        const BAD_USERNAME_PASSWORD = 2;
    
        public static $Username = '';
        public static $Err = null;
        const AUTH_METHOD = "MySQL";
        
        static function Authenticate($username,$password = NULL,$usecas = false) {
            require_once("auth/" . self::AUTH_METHOD . ".php");
            $classname = self::AUTH_METHOD . "Authentication";
            
            // workaround to allow CAS usage
            if ($usecas) {
            	// make sure the person is logged into CAS
            	$username = phpCAS::getUser();
            	if (isset($username)) {
            		// get their info from the db
            		$userinfo = DBM::FetchRow("SELECT * FROM guests WHERE email LIKE '$username';");
            		if (!is_array($userinfo)) {
            			// if they don't have a guest entry then create one.
            			DBM::Execute("INSERT INTO guests (name,email,approved,created,expires,override_auth) VALUES " .
            				"('$username','$username',1," . time() . ",0,2);");
            			$userinfo = DBM::FetchRow("SELECT * FROM guests WHERE email LIKE '$username';");
            		}
            		// set the proper values
            		SessionManager::Set('user_id',$userinfo['id']);
            		SessionManager::Set('auth_level',$userinfo['override_auth']);
            		SessionManager::Set('authenticated',true);
            		SessionManager::Set('username',$userinfo['email']);
            		self::$Username = $username;
            		
            		return true;
            	}
            	else return false;
            }
            else {
	            $eval = "\$auth = new $classname();";
	            eval($eval);
	            if ($auth->Authenticate($username,$password)) {
	                SessionManager::Set('user_id',$auth->GetUserID());
	                SessionManager::Set('auth_level',$auth->GetAuthLevel());
	                SessionManager::Set('authenticated',true);
	                SessionManager::Set('username',$username);
	                self::$Username = $username;
	                
	                return true;
	            }
	            else {
	                if ($auth->GetError()) {
	                    self::$Err = $auth->GetError();
	                }
	            
	                return false;
	            }
	        }
        }
        
        static function GetErrorDetails($error = null) {
            if ($error == null) $error = self::$Err;
                        
            $errobj = null;
            switch ($error) {
                case self::ACCOUNT_EXPIRED: $errobj = new Error("Account Expired","Your account has expired. Please request a new one <a href='guest.php'>here</a>.",'warning'); break;
                case self::BAD_USERNAME_PASSWORD: $errobj = new Error("Bad Username or Password","You entered a bad username and/or password.  Please try again."); break;
                default: $errobj = new Error("Success!","Authentication Successful"); break;
            }
            
            return $errobj;
        }
        
        static function AuthLevelMatches($levels) {
            if (!is_array($levels)) $levels = array($levels);
            if (self::GetAuthLevel() != AuthConstants::NOT_LOGGED_IN && $levels[0] == AuthConstants::ALL_LOGGED_IN) return true;
            
            foreach ($levels as $level) {
                if ($level == self::GetAuthLevel() || $level == AuthConstants::EVERYONE) return true;
            }
            return false;
        }
        static function CheckPermissions($levels) {
            return self::AuthLevelMatches($levels);
        }
        
        static function ListingBelongsTo($listingid,$landlord = null) {
            if ($landlord == null && self::AuthLevelMatches(AuthConstants::ADMINISTRATORS)) return true;
            else if (self::AuthLevelMatches(AuthConstants::LANDLORDS)) {
                if ($landlord == null) 
                    $landlord = AuthManager::GetUserID();
               
                if (!is_numeric($listingid))
                    ErrorMessage::Show("Error","There was an error getting listing information for listing $listingid.  Please contact <a href='contactus.php'>offcampus@union.rpi.edu</a> with a description of what you were trying to do.");
                $landlord_info = DBM::FetchRow("SELECT id,landlordid FROM listings WHERE id=$listingid;");                
                $landlordid = $landlord_info['landlordid'];
                
                if ($landlordid == $landlord) 
                    return true;
            }
            else return false;
        }
        
        static function GetError() {
            return self::$Err;
        }
        
        static function GetUsername() {
            if (self::$Username == NULL) {
                self::$Username = SessionManager::Get("username");
            }
            return self::$Username;
        }
        
        static function GetUserID($email = NULL) {
			if (!is_null($email) && !empty($email)) {
				$query = "SELECT * FROM guests WHERE email LIKE '$email';";
				$res = DBM::FetchRow($query);
				return $res['id'];
			}
            else {
                $id = SessionManager::Get("user_id");
                if (empty($id)) {
                    FatalMessage::Show("Session Error","Error: Your session has expired due to inactivity.  Please log in again using the links on the Menu bar. <pre>" . print_r(debug_backtrace(true),true) . "</pre>");
                    Functions::PrintFooter();
                    exit;
                }
                else return $id;
            }
        }
        
        static function GetAuthLevel() {
            $authlevel = SessionManager::Get("auth_level");
            if ($authlevel == null) return -1;
            else return $authlevel;
        }
    }
?>
